package com.skynet.supervision.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.skynet.supervision.common.ErrCode;
import com.skynet.supervision.common.Result;
import lombok.SneakyThrows;

import javax.annotation.Nonnull;
import java.util.Optional;

/**
 * @author xuchao
 * @date 2023-03-08 14:07
 */
public final class PageUtils {
    private PageUtils() {

    }

    @SneakyThrows
    public static <T> Page<T> checkAndBuildPage(Integer page, Integer pageSize) {
        return checkAndBuildPage(page, pageSize, 10);
    }

    @SneakyThrows
    public static <T> Page<T> checkAndBuildPage(Integer page, Integer pageSize, @Nonnull Integer defaultPageSize) {
        long p = Optional.ofNullable(page).orElse(1);
        long ps = Optional.ofNullable(pageSize).orElse(defaultPageSize);
        if (p < 1) {
            throw Result.failure(ErrCode.BAD_PARAM, "pageNo不能小于1").wrap();
        }
        if (ps < 1) {
            throw Result.failure(ErrCode.BAD_PARAM, "pageSize不能小于1").wrap();
        }
        return new Page<>(p, ps);
    }
}
